package com.ztgf.pay.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.pay.common.config.YmlConfig;
import com.ztgf.pay.mapper.PayFundSyncMapper;
import com.ztgf.pay.models.bo.PayFundSyncSaveBO;
import com.ztgf.pay.models.dto.PayFundSyncDTO;
import com.ztgf.pay.models.service.IPayFundDetailsService;
import com.ztgf.pay.models.service.IPayFundSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 资金明细同步表控制器
 *
 * @author mxli
 * @Date 2023-02-22 20:47:02
 */
@DubboService
@Slf4j
public class PayFundSyncServiceImpl extends ServiceImpl<PayFundSyncMapper, PayFundSyncDTO> implements IPayFundSyncService{

    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private IPayFundDetailsService payFundDetailsService;

    @Override
    public boolean add(PayFundSyncSaveBO saveBO) {
        PayFundSyncDTO dto = new PayFundSyncDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public PayFundSyncDTO getLastDTO() {
        return this.baseMapper.getLastDTO();
    }

    @Override
    public void saveSync(Date beginDate, Date endDate) {
        Date syncDate = beginDate;
        while (syncDate.getTime() < endDate.getTime()){
            int status = 0;
            try {
                payFundDetailsService.saveSync(syncDate);
                status = 2;
            } catch (Exception e){
                log.error("----saveSync:" + syncDate, e);
            }

            save(syncDate, status);
            syncDate = DateUtils.addDay(syncDate, 1);
        }
    }

    private void save(Date syncDate, int status){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("sync_time", syncDate);
        PayFundSyncDTO dto = new PayFundSyncDTO();
        dto.setSyncTime(syncDate);
        dto.setStatus(status);
        if(!this.update(dto, wrapper)){
            Long id = ymlConfig.getPkId();
            dto.setId(id);
            this.insert(dto);
        }
    }
}
